package com.Webserver.controller;

import com.Webserver.http.HttpRequest;
import com.Webserver.http.HttpResponse;
import com.Webserver.vo.Article;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

/**
 * 处理文章相关业务
 */
public class ArticleController {

    private static String articlesName = "./articles/";

    static {
        File userDir = new File(articlesName);
        if (!userDir.exists()) {
            userDir.mkdirs();
        }
    }
    //用于处理发表文章
    public void writeArticle(HttpRequest request, HttpResponse response) {
        System.out.println("写入中...");
        String title = request.getParameter("title");
        String content = request.getParameter("content");
        String author = request.getParameter("author");

        if (title == null || content == null || author==null) {
            response.setEntity(new File("./webapps/myweb/article_fail.html"));
            return;
        }
        Article article = new Article(title,content,author);
        try (
                FileOutputStream fos = new FileOutputStream(articlesName + author + ".obj");
                ObjectOutputStream oot = new ObjectOutputStream(fos);
        ) {
            oot.writeObject(article);
            response.setEntity(new File("./webapps/myweb/article_success.html"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("文章发表完毕!!!");
    }
}
